﻿using System;
using nRoute.Services;
using nRoute.Samples.Sudoku.Model;
using nRoute.Components.Composition;
using System.ComponentModel;

namespace nRoute.Samples.Sudoku.Services
{
    [MapService(typeof(IGenerateGameService), Lifetime = InstanceLifetime.PerInstance)]
    public class GenerateGameService : 
        BackgroundWorker, IGenerateGameService
    {
       
#region IGenerateGameService Members

        public void GenerateGame(GameLevel level, Action<Game> gameCallback)
        {
            if (gameCallback == null) throw new ArgumentNullException("gameCallback");
            RunWorkerAsync(new GameInfo()
                           {
                               GameLevel = level, 
                               GameCallback = gameCallback
                           });
        }

#endregion

#region Overrides

        protected override void OnDoWork(DoWorkEventArgs e)
        {
            // create game
            var _gameInfo = (GameInfo)e.Argument;
            var _game = new Game() { Level = _gameInfo.GameLevel};
            _game.NewGame();
            _gameInfo.GameResult = _game;

            // and return
            e.Result = _gameInfo;
        }

        protected override void OnRunWorkerCompleted(RunWorkerCompletedEventArgs e)
        {
            var _gameInfo = (GameInfo)e.Result;
            if (_gameInfo != null) _gameInfo.GameCallback(_gameInfo.GameResult);
        }

#endregion

#region Nested Class

        private class GameInfo
        {
            public GameLevel GameLevel { get; set; }

            public Action<Game> GameCallback { get; set; }

            public Game GameResult { get; set; }
        }

#endregion

    }
}
